import React, { Component } from 'react';
import { Platform, PixelRatio, StyleSheet, Text, View, Image, Dimensions, TouchableOpacity, Alert, Linking, NativeModules, BackHandler } from "react-native";
import { style } from '../../theme/style';
import { Common } from '../../component/common/Common';
import { STORAGE_CONSTANT } from '../../config/storage';
import ToastUtil from '../../utils/toast';
import StorageHelper from '../../utils/storageHelper';
import moment from 'moment';
import HotUpdate from '../../components/update/HotUpdate';
import HotUpdatePage from '../../components/update/HotUpdatePage';
import AppUpdatePage from '../../components/update/AppUpdatePage';
import AppUpdate from '../../components/update/AppUpdate';
import { GLOBAL } from '../../config/global';

var appInfo = require('react-native-device-info');

const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;


export class AboutUsPage extends Component {

	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '关于我们',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../imgs/goBackEmpty.png')} />),
			headerStyle: {
				elevation: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.params = this.props.navigation.state.params || {};
		this.state = {
			appHotVersion: '',
			showHotUpdate: false,
			showAppUpdate: false
		}
		this.checkingHotUpdate = false;
		this.checkingAppUpdate = false;
	}

	async componentWillMount() {
		const appVersion = await StorageHelper.get(STORAGE_CONSTANT.APP_VERSION);
		const currAppVersion = appInfo.getVersion();
		if (appVersion && currAppVersion != appVersion) {
			//应用版本更新了
			StorageHelper.remove(STORAGE_CONSTANT.APP_HOT_VERSION);
			StorageHelper.set(STORAGE_CONSTANT.APP_VERSION, currAppVersion);
		}
		const appHotVersion = await StorageHelper.get(STORAGE_CONSTANT.APP_HOT_VERSION);
		this.setState({
			appHotVersion: appHotVersion
		})
	}

	// 检查热更新
	async checkHotUpdate() {
		if (this.checkingHotUpdate) return;
		this.checkingHotUpdate = true;
		let updateInfo = await HotUpdate.checkUpdate();
		if (updateInfo.update) {
			this.setState({ showHotUpdate: true, showAppUpdate: false }, async () => {
				const { syncStatus } = await HotUpdate.doUpdate(this.downloadProgressCallback);
				if (syncStatus === 1) {
					await Dictionary.updated(); // 热更成功 更新数据字典
					this.setState({ showHotUpdate: false }, async () => {
						this.timer = setTimeout(() => {
							HotUpdate.restart();
						}, 500)
					})
				} else {
					this.setState({ showHotUpdate: false });
				}
			})
		} else {
			this.checkingHotUpdate = false;
			HotUpdate.getCurrentPackage().then(updateInfo => {
				(updateInfo && updateInfo.label) && StorageHelper.set(STORAGE_CONSTANT.APP_HOT_VERSION, updateInfo.label);
			})
		}
	}

	// 检查版本更新
	async checkAppUpdate() {
		if (this.checkingAppUpdate) return;
		this.checkingAppUpdate = true;
		//手动检查更新时，清楚忽略版本
		await StorageHelper.set(STORAGE_CONSTANT.VERSION_IGNORE, {
			versionIgnoreCode: null,
			versionIgnoreTime: new Date()
		});
		let versionInfo = await AppUpdate.checkUpdate();
		this.checkingAppUpdate = false;
		if (versionInfo) {
			this.setState({ versionInfo: versionInfo, showAppUpdate: !!versionInfo, showHotUpdate: false });
		} else {
			ToastUtil.showInfo('当前是最新版本');
		}
	}

	//更新
	goUpdate() {
		this.checkAppUpdate();
	}

	goHotUpdate() {
		this.checkHotUpdate()
	}

	async getRegisteID() {
		const REGISTRATION_ID = await StorageHelper.get(STORAGE_CONSTANT.REGISTRATION_ID);
		ToastUtil.showInfo(REGISTRATION_ID ? '设备ID为：' + REGISTRATION_ID : '无');
	}

	//打点话
	cantact() {
		Alert.alert('联系我们', '400-XXX-XXX', [
			{ text: '取消' },
			{ text: '呼叫', onPress: () => { this._call() } }
		]);
	}

	_call() {
		Linking.canOpenURL('tel:13218078256').then(supported => {
			if (!supported) {
				console.log('Can\'t handle url: ' + 'tel:13218078256');
			} else {
				return Linking.openURL('tel:13218078256');
			}
		}).catch(err => console.error('An error occurred', err));
	}

	render() {
		const currVersion = appInfo.getVersion();  //versionName
		let { showHotUpdate, showAppUpdate, versionInfo } = this.state;
		return (
			<View style={styles.container}>
				{showHotUpdate ? <HotUpdatePage isVisible={showHotUpdate} /> : null}
				{showAppUpdate ? <AppUpdatePage versionInfo={versionInfo} isVisible={showAppUpdate} ignore={() => this.setState({ showAppUpdate: false })} /> : null}
				<View style={styles.logBox}>
					<Image source={require('../../imgs/log.png')} style={{ width: 80 * scale, height: 80 * scale }} />
					<Text style={styles.logTitle}>应用版本：{currVersion}</Text>
					{this.state.appHotVersion ? (<Text style={{ fontSize: 14 * scale, marginBottom: 15, color: style.color.dark }}>热包版本：{this.state.appHotVersion}</Text>) : (null)}
				</View>
				<View style={[styles.listBox, styles.listBoxWithTopBorder]}>
					<TouchableOpacity style={[styles.list, styles.listActive]} onPress={() => this.goUpdate()} activeOpacity={1} >
						<Text style={styles.listLeft}>新版本检测</Text>
						<View style={styles.listRight}>
							{GLOBAL.APP_HAS_UPDATE ? (<Text style={styles.listRightText}>{this.params['appVersionInfo']['versionNo']}</Text>) : (null)}
							<Image style={styles.listRightImg} source={require('../../imgs/arrow-left.png')} />
						</View>
					</TouchableOpacity>
				</View>
				<View style={[styles.listBox, styles.listBoxWithTopBorder]}>
					<TouchableOpacity style={[styles.list, styles.listActive]} onPress={() => this.goHotUpdate()} activeOpacity={1} >
						<Text style={styles.listLeft}>新热包检测</Text>
						<View style={styles.listRight}>
							<Image style={styles.listRightImg} source={require('../../imgs/arrow-left.png')} />
						</View>
					</TouchableOpacity>
				</View>
				<View style={[styles.listBox, styles.listBoxWithTopBorder]}>
					<TouchableOpacity style={[styles.list, styles.listActive]} onPress={() => this.getRegisteID()} activeOpacity={1} >
						<Text style={styles.listLeft}>查询消息推送设备ID</Text>
						<View style={styles.listRight}>
							<Image style={styles.listRightImg} source={require('../../imgs/arrow-left.png')} />
						</View>
					</TouchableOpacity>
				</View>
				<View style={styles.listBox}>
					<TouchableOpacity style={[styles.list, styles.listActive]} onPress={() => { this.props.navigation.navigate('AppInfoPage', this.params['appVersionInfo']) }} activeOpacity={1} >
						<Text style={styles.listLeft}>版本说明</Text>
						<Image style={styles.listRightImg} source={require('../../imgs/arrow-left.png')} />
					</TouchableOpacity>
				</View>
				{/* <View style={styles.listBox}>
					<TouchableOpacity style={[styles.list, styles.listActive]} onPress={() => this.cantact()} activeOpacity={1} >
						<Text style={styles.listLeft}>联系我们</Text>
						<Image style={styles.listRightImg} source={require('../../imgs/arrow-left.png')} />
					</TouchableOpacity>
				</View> */}
				<View style={styles.titleBox}>
					<Text style={styles.titleText}>Copyright © {moment().format('YYYY')} 中化石化销售有限公司</Text>
				</View>
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	logBox: {
		flexDirection: 'column',
		alignItems: 'center',
		marginTop: 52 * scale,
	},
	titleBox: {
		flex: 1,
		flexDirection: 'column',
		justifyContent: 'flex-end',
		alignItems: 'center',
		marginBottom: 42 * scale
	},
	titleText: {
		fontSize: 13 * scale,
		color: style.color.dark
	},
	logTitle: {
		fontSize: 14 * scale,
		color: style.color.dark,
		marginTop: 22 * scale,
		marginBottom: 20 * scale
	},
	listBox: {
		backgroundColor: '#fff',
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
	},
	listBoxWithTopBorder: {
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.border,
	},
	list: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		height: 52 * scale,
		width: '100%',
	},
	listActive: {
		borderBottomWidth: 0,
	},
	listLeft: {
		fontSize: 14 * scale,
		color: style.color.dark
	},
	listRight: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center'
	},
	listRightText: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
		marginRight: 8 * scale,
	},
	listRightImg: {
		width: 6 * scale,
		height: 11 * scale,
	},
})